#include <assert.h>
#include <string.h>

#include "http.h"

// 函数：获取文件扩展名并返回相应的Content-Type
const char* guessContentType(const char* filename) {
    assert(filename != NULL);

    // 找到最后一个 '.' 的位置
    const char* ext = strrchr(filename, '.');
    if (ext == NULL) return "application/octet-stream";

    // 查找表：扩展名与Content-Type的映射
    const struct {
        const char* extension;
        const char* contentType;
    } mimeTypes[] = {
        {".html", "text/html"},
        {".htm", "text/html"},
        {".css", "text/css"},
        {".js", "application/javascript"},
        {".jpg", "image/jpeg"},
        {".jpeg", "image/jpeg"},
        {".png", "image/png"},
        {".gif", "image/gif"},
        {".json", "application/json"},
        {".pdf", "application/pdf"},
        {".xml", "application/xml"},
        {".zip", "application/zip"},
        {".mp4", "video/mp4"},
        {".webp", "application/webp"},
        {".webx", "application/webx"},
        {".webm", "application/webm"},
        {".txt", "text/plain"},
        {NULL, NULL} //标记结束
    };

    // 遍历查找表，匹配扩展名
    for (int i = 0; mimeTypes[i].extension != NULL; i++) {
        if (strcmp(ext, mimeTypes[i].extension) == 0) {
            return mimeTypes[i].contentType;
        }
    }

    // 默认返回二进制流
    return "application/octet-stream";
}
